<template>
  <div class="w-full h-full overflow-hidden relative" @click="handleClick">
    <template v-if="state.loading && state.messages.length == 0">
      <div class="w-full h-[56px] flex justify-center items-center my-[3px]">
        <van-loading type="spinner" color="#000" size="26" />
      </div>
    </template>
    <virtual-list ref="virtualListRef" :list="state.messages" @is-scroll-bottom="isScrollBottom">
      <template #default="{ source }: MsgItem">
        <MsgItem :item="source" />
      </template>
    </virtual-list>
    <div
      @click="scrollToBottom"
      v-if="showChatMore"
      class="absolute bottom-[5px] right-[15px] z-50 w-[50px]"
    >
      <img class="w-full h-full" src="@/assets/images/chat-more.png" alt="" />
    </div>
  </div>
</template>
<script lang="ts" setup>
import $bus from "@/utils/bus";
import VirtualList from "@/components/virtual-list.vue";

import MsgItem from "./msg-item.vue";
import { cloneDeep } from "lodash-es";
import { useUserStore } from "@/store/modules/user";
import { storeToRefs } from "pinia";

interface MsgItem {
  source: ChatHistoryMo;
}

const emit = defineEmits(["close"]);
const state = inject<CustomerState>("state") as CustomerState;
const userId = inject("userId") as number;
const contentId = inject("contentId") as string;
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const virtualListRef = ref();

const showChatMore = computed(() => {
  if (!state.autoScrollToBottom) {
    return true;
  } else {
    return false;
  }
});

// 设置为是否滚动到底部
const isScrollBottom = (flag: boolean) => {
  state.autoScrollToBottom = flag;
};

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  virtualListRef.value?.scrollToBottom();
};

const watchSocket = () => {
  // 监听房间消息
  $bus.on("kefu-msg", async data => {
    if (String(userId) === String(data.user_id) || data.user_id == `r_${userInfo.value?.RoomId}`) {
      const params = {
        Avatar: data.avatar,
        ChatcontentId: Number(contentId),
        CreatedAt: data.time,
        Id: Date.now(),
        Msg: data.content,
        MsgType: data.msg_type,
        NickName: data.nick_name,
        Type: data.msg_type,
        UserId: data.user_id
      };
      let messages = cloneDeep(state.messages);
      if (messages.length >= 600) {
        messages = messages.slice(200, messages.length + 1);
      }
      messages.push({
        ...params
      } as ChatHistoryMo);
      state.messages = cloneDeep(messages);

      await nextTick();
      scrollToBottom();
    }
  });
};

const handleClick = () => {
  emit("close");
};

onMounted(() => {
  watchSocket();
});

defineExpose({
  scrollToBottom
});
</script>
<style lang="scss" scoped>
.chat-box {
  margin: 0 10px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  overflow: hidden;
  &:first-child {
    margin-top: 10px;
  }
}
.mine-chat-box {
  .chat-name {
    color: #666;
    background-color: transparent;
  }
  .chat-message {
    background-color: #95eb69;
    &::after {
      content: "";
      position: absolute;
      width: 0px;
      height: 0px;
      right: -13px;
      left: auto;
      top: 10px;
      border: 7px solid transparent;
      border-left: 7px solid #95eb69;
    }
  }
}
.chat-message {
  &::after {
    content: "";
    position: absolute;
    width: 0px;
    height: 0px;
    left: -13px;
    top: 10px;
    border: 7px solid transparent;
    border-right: 7px solid #fff;
  }
}
</style>
<style lang="css" scoped>
.chat-name {
  @apply h-[18px] leading-[18px] px-[5px] rounded-[4px] bg-[#4fa3f7] inline-block text-[12px] text-[#fff] mb-[4px];
}
.chat-message {
  @apply bg-[#fff] break-all inline-block p-[10px] mb-[10px] rounded-[6px] relative text-[14px] min-w-[40px];
}
</style>
